package com.example.xf_evaluate

import android.os.Handler
import android.os.Looper
import android.util.Log

import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import com.iflytek.aiui.vad.sdk.Vad
import com.iflytek.aiui.vad.sdk.VadConstant

/** XfEvaluatePlugin */
class XfEvaluatePlugin : FlutterPlugin, MethodCallHandler {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private lateinit var channel: MethodChannel

    /**
     * 用于线程切换
     */
    private val mHd = Handler(Looper.getMainLooper())

    private var mPreTimeout = "sendTimeOut"
    private var mPosTimeout = "stopRecord"

    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        Log.d("ebook TAG", "onAttachedToEngine: 初始化11111")
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "xf_evaluate")
        channel.setMethodCallHandler(this)
        Log.d("ebook TAG", "onAttachedToEngine: 初始化")
        VadManager.init(flutterPluginBinding.applicationContext)
    }

    override fun onMethodCall(call: MethodCall, result: Result) {
//        Log.d("ebook TAG", "onMethodCall: ${call.method},arguments = ${call.arguments} $channel")
        when (call.method) {
            "asyncVadConfig" -> {
                mPreTimeout = call.argument("status_bos_timeout") ?: "sendTimeOut"
                mPosTimeout = call.argument("status_finish") ?: "sendTimeOut"
            }

            "getPlatformVersion" -> {
                result.success("Android ${android.os.Build.VERSION.RELEASE}")
            }

            "destroyVadListener" -> {
                VadManager.setListener(null)
            }

            "setVadListener" -> {
                VadManager.setListener(getVadListener())
            }

            "detect" -> {
                VadManager.detect(
                    (call.argument("data") as ByteArray?) ?: ByteArray(0),
                    (call.argument("len") as Int?) ?: 0
                )
            }

            "resetVad" -> {
                VadManager.reset()
            }

            else -> {
                result.notImplemented()
            }
        }
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }

    var mVadListener: Vad.VadListener? = null

    fun getVadListener(): Vad.VadListener? {
        if (mVadListener == null) {
            mVadListener = object : Vad.VadListener {
                override fun onAuthSuccess() {
                }

                override fun onResult(status: Int, p1: ByteArray?, p2: Int, p3: Int) {
                    when (status) {
                        VadConstant.STATUS_BOS_TIMEOUT -> {
                            Log.e("XfEvaluatePlugin", "onResult: 前置超时")
//              NLogger.d(TAG, "getVadListener STATUS_BOS_TIMEOUT 前置超时")
//              mSDKHandler?.sendTimeOut()
                            mHd.post {
                                channel.invokeMethod(
                                    "vadCallback",
                                    mapOf("eventType" to mPreTimeout)
                                )
                            }


                        }

                        VadConstant.STATUS_FIND_BOS -> {
//              NLogger.d(TAG, "getVadListener STATUS_FIND_BOS")
//                            mSDKHandler?.sendTimeOut()
                        }

                        VadConstant.STATUS_CONTINUE -> {
//              NLogger.d(TAG, "getVadListener STATUS_CONTINUE")
                        }

                        VadConstant.STATUS_FIND_EOS -> {
//              NLogger.d(TAG, "getVadListener STATUS_FIND_EOS")
                        }

                        VadConstant.STATUS_FINISH -> {
//              NLogger.d(TAG, "getVadListener STATUS_FINISH 后置超时")
//              stopRecord()
                            Log.e("XfEvaluatePlugin", "onResult: 后置超时")
                            mHd.post {
                                channel.invokeMethod(
                                    "vadCallback",
                                    mapOf("eventType" to mPosTimeout)
                                )
                            }
                        }
                    }
                }

                override fun onError(p0: Int, p1: String?) {
                }

            }
        }
        return mVadListener
    }
}
